package com.hopu.shiro_demo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

import java.util.Scanner;

public class ShiroTest2 {

    @Test
    public void testShiroRealm(){
        //创建安全管理器的工厂,参数是ini文件的路径
        Factory factory = new IniSecurityManagerFactory("classpath:shiro-4.ini");
        //获得安全管理器
        SecurityManager mgr = (SecurityManager) factory.getInstance();
        //设置安全管理器
        SecurityUtils.setSecurityManager(mgr);
        //创建Subject对象，用于调用用户的权限信息
        Subject subject = SecurityUtils.getSubject();
        //判断用户如果没有进行验证，就执行登录验证
        if(!subject.isAuthenticated()){
            //创建保存账号和密码的符号Token
            UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123456");
            try {
                //对账号密码进行登录验证,验证失败会抛出异常
                subject.login(token);
                System.out.println("登录成功");
                //判断用户具有的角色
                System.out.println("是否有admin角色"+subject.hasRole("admin"));
                System.out.println("是否有添加商品权限"+subject.isPermitted("insert-goods"));
                System.out.println("是否有删除商品权限"+subject.isPermitted("delete-goods"));
                System.out.println("是否有更新商品权限"+subject.isPermitted("update-goods"));
                System.out.println("是否有查询商品权限"+subject.isPermitted("select-goods"));
            }catch (Exception ex){
                ex.printStackTrace();
                System.out.println("登录失败");
            }
            //注销用户
            subject.logout();
        }
    }
}
